import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author jh.pei
 * @date 2024/10/17 10:29
 */
public class 链表内指定区间反转 {
    List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    public static void main(String[] args) {
        ListNode lList = ListNode.getLList(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
        ListNode listNode = reverseBetween(lList, 2, 2);
        ListNode.print(listNode);
    }

    public static ListNode reverseBetween (ListNode head, int m, int n) {
        // write code here
        ListNode headNew = new ListNode(-1);
        headNew.next = head;
        ListNode cur = headNew;
        ListNode preLeftNode = null;
        ListNode rightNode = null;
        int index = 0;
        while(cur != null) {
            if (index == m-1) {
                preLeftNode = cur;
            }
            if (index == n) {
                rightNode = cur;
                break;
            }
            cur = cur.next;
            index++;
        }
        // 翻转链表
        ListNode leftNode = preLeftNode.next;
        ListNode rightNodeNext = rightNode.next;

        rightNode.next = null;
        preLeftNode.next = null;


        reverseLinkedList(leftNode);

        preLeftNode.next = rightNode;
        leftNode.next = rightNodeNext;

        return headNew.next;
    }


    public static void reverseLinkedList(ListNode head) {
        ListNode pre = null;
        ListNode current = head;
        while(current != null) {
            ListNode curNext = current.next;
            current.next = pre;
            pre = current;
            current = curNext;
        }
    }
}
